import pandas as pd
from back_end.helpers import datetime
from back_end.hsa.data_display import keywords_reader

class KeywordTrends():
    def __init__(self, length, step, k=10):
        start_date, end_date = datetime.get_date_range(length * step)
        self.__top_k_words = keywords_reader.get_top_k_words_in_range(start_date, end_date, k)
        self.__word_counts = keywords_reader.get_word_counts_in_range(start_date, end_date, self.__top_k_words)
        self.__df = pd.DataFrame(self.__get_records(start_date, length, step))

    def to_df(self):
        return self.__df
    
    def __get_records(self, start_date, length, step):
        records = []
        for date in datetime.length_iterator(start_date, length, step):
            for word in self.__top_k_words:
                records.append(self.__get_record(date, word, step))
        return records if records else [{'日期': '未知日期', '词汇': '未知词汇', '数量': 0}]
        
    def __get_record(self, date, word, length):
        return {
            '日期': date,
            '词汇': word,
            '数量': sum(self.__word_counts.get(d, {}).get(word, 0) for d in datetime.length_iterator(date, length))
        }
